/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.balisunrise.swing.components.util;

import java.io.Serializable;
import java.util.List;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.balisunrise.application.Application;
import org.balisunrise.builder.FactoryException;
import org.balisunrise.common.GridSelectionListener;
import org.balisunrise.common.LineSelectionEvent;

/**
 *
 * @author glacuo
 */
public class ListSelectionListenerImpl implements ListSelectionListener{

    private JTable table;
    private List<GridSelectionListener> gridSelectionListeners;
    private LineSelectionEvent evt;

    public void valueChanged(ListSelectionEvent e) {

        if (e.getValueIsAdjusting())
            return;

        DefaultListSelectionModel dlsm =
            (DefaultListSelectionModel) e.getSource();

        int selectedIndex = dlsm.getMinSelectionIndex();

        fireLineActivatedEvent(e.getSource());

        if(table.getModel().getRowCount() == selectedIndex + 1)
            fireLastLineEvent();
    }

    public List<GridSelectionListener> getGridSelectionListeners() {
        return gridSelectionListeners;
    }

    public void setGridSelectionListeners(
            List<GridSelectionListener> gridSelectionListeners) {
        this.gridSelectionListeners = gridSelectionListeners;
    }

    public JTable getTable() {
        return table;
    }

    public void setTable(JTable table) {
        this.table = table;
        this.table.getSelectionModel().addListSelectionListener(this);
    }

    public void fireLineActivatedEvent(Object source){

        Serializable entity = null;

        Object selectedRow = table.getSelectedRow();

        if(selectedRow instanceof Serializable)
            entity = (Serializable) selectedRow;

        evt = null;
        try{
            evt = Application.get().getFactory()
                    .createLineSelectedEvent(entity, source);
        }catch (FactoryException fex){
            System.out.println("Falha ao criar LineSelectedEvent:\n" +
                    fex.getMessage());
        }

        for (GridSelectionListener gsl : gridSelectionListeners) {
            gsl.lineSelected(evt);
        }
    }

    public void fireLastLineEvent(){
        for (GridSelectionListener gsl : gridSelectionListeners) {
            gsl.lastLineSelected(evt);
        }
    }
}
